import React, { useEffect, useState } from 'react';
import { connect, Dispatch } from 'umi';

import styles from './style.less';

import { Card, Tooltip } from 'antd';

import ChartTypes from '@/components/Charts/ChartTypes';

// @ts-ignore
import { WidthProvider, Responsive } from 'react-grid-layout';
const ResponsiveReactGridLayout = WidthProvider(Responsive);

import { subscribeWidgetsItem, IndexDetailItem, GridLayoutsItem } from '../type';
import { ConnectState } from '@/models/connect';

import Icon from '@/components/Icon';
import WidgetBoard from '@/components/WidgetBoard';
import Widget from '@/components/Widget';

interface SubscribeProps {
  dispatch: Dispatch;
  indexDetail: IndexDetailItem;
  subscribeWidgets: Array<subscribeWidgetsItem>;
}

const Subscribe: React.FC<SubscribeProps> = (props) => {
  const { dispatch, subscribeWidgets, indexDetail } = props;
  const [editing, setEditing] = useState(false); // 是否编辑中
  // 订阅的指标列表
  const widgetList =
    subscribeWidgets && subscribeWidgets.length
      ? subscribeWidgets.map((widget: any, idx: any) => {
          return { ...widget, ...{ widgetId: widget.id, widgetName: widget.name } };
        })
      : [];

  // 初始化移动各个模块配置
  const layouts: { lg: Array<GridLayoutsItem> } = { lg: [] };
  widgetList.map((item) => {
    let defaultObj = {
      x: 0,
      y: 0,
      w: 12,
      h: 9,
      i: String(item.subscribeId),
    };
    if (item.position) {
      defaultObj = { ...defaultObj, ...JSON.parse(item.position) };
    } else {
      // 不存在预设值，使用默认
      const configs = JSON.parse(item.config);

      // 根据图表类型获得默认高度
      if (configs) {
        const { selectedChart, metrics, cols } = configs;
        switch (selectedChart) {
          case ChartTypes.Table:
            defaultObj.h = 10;
            // 判断是否KPI表格类型
            if (metrics && metrics.length == 2 && cols && cols.length == 0) {
              defaultObj.h = 5;
            }
            break;
          case ChartTypes.Line:
            defaultObj.h = 8.2;
            break;
          case ChartTypes.Bar:
            defaultObj.h = 8.2;
            break;
          case ChartTypes.Pie:
            defaultObj.h = 8.2;
            break;
          default:
            defaultObj.h = 9;
        }
      }
    }

    layouts.lg.push(defaultObj);
  });

  // 移动模板配置项
  const gridConfig = {
    autoSize: true,
    rowHeight: 30, // 行的静态高度
    margin: [16, 16],
    draggableHandle: '.ant-card-head-title', // 可拖动位置
    breakpoints: { lg: 1200, md: 996, sm: 768, xs: 480, xxs: 0 }, // 屏幕大小区分界限
    cols: { lg: 12, md: 12, sm: 12, xs: 12, xxs: 12 }, // 设置网格数
  };

  // 拖动结束&更改大小结束 保存排版
  const preserve = (layout: Array<GridLayoutsItem>) => {
    const positionsArr: Array<any> = [];
    layout.map((item: GridLayoutsItem) => {
      const { x, y, w, h, i } = item;
      const obj = JSON.stringify({
        x,
        y,
        w,
        h,
      });
      positionsArr.push({ id: Number(i), position: obj });
    });
    dispatch({
      type: 'subscribe/preservePosition',
      payload: { positions: positionsArr },
    });
  };

  // 获取我的订阅列表
  useEffect(() => {
    dispatch({
      type: 'subscribe/fetchSubscribeWidgets',
    });
     // 清除查看的指标详情数据 解决各页面查看指标详情相互影响
     dispatch({
      type: 'widget/fetchIndexDetail',
      payload: {},
    });
  }, []);

  return (
    <div className={styles.subscribe}>
      {indexDetail.dataRecord && indexDetail.configs ? ( // 指标详情
        <Widget parentTitle="我的订阅" />
      ) : (
        <Card
          bordered={false}
          extra={
            <div className={styles.edit}>
              {editing ? (
                <Tooltip title="完成编辑">
                  <span
                    onClick={() => {
                      setEditing(false);
                    }}
                  >
                    <Icon type="editing" width={20} height={20} />
                  </span>
                </Tooltip>
              ) : (
                <Tooltip title="点击编辑">
                  <span
                    onClick={() => {
                      setEditing(true);
                    }}
                  >
                    <Icon type="edit" width={20} height={20} />
                  </span>
                </Tooltip>
              )}
            </div>
          }
        >
          <ResponsiveReactGridLayout
            className="layout"
            {...gridConfig}
            layouts={layouts}
            onDragStop={preserve}
            onResizeStop={preserve}
          >
            {widgetList.map((item, i) => (
              <div key={String(item.subscribeId)} className={styles.gridItem}>
                <WidgetBoard widget={item} editing={editing} />
              </div>
            ))}
          </ResponsiveReactGridLayout>
        </Card>
      )}
    </div>
  );
};

export default connect(({ widget, subscribe }: ConnectState) => ({
  subscribeWidgets: subscribe.subscribeWidgets,
  indexDetail: widget.indexDetail,
}))(Subscribe);
